package com.example.java.base.concurrency.threadpool;

import com.example.java.base.concurrency.threadpool.task.ShutDownTask;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;


/**
 * A8_ShutDown:演示关闭线程池
 *
 * @author zhangxiaoxiang
 * @date 2020/11/5
 */
@Slf4j
public class A8ShutDown {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        //1000测试
        for (int i = 0; i < 100; i++) {
            executorService.execute(new ShutDownTask());
        }
        Thread.sleep(1500);
        //强制关闭,比较暴力
        executorService.shutdownNow();
        // List<Runnable> runnableList = executorService.shutdownNow();
        //       这些强制关闭的线程需要进一步处理,不可能直接暴力关闭的哈
        //-------------------------------------------------------------------------------
        //shutdown()优雅关闭线程,发出指令后,把在执行的线程先执行完了再关闭,isShutdown()判断是否已经关闭
        log.info("是否结束线程:" + executorService.isShutdown());
        executorService.shutdown();
        log.info("是否结束线程:" + executorService.isShutdown());
        // 当线程执行了shutdown()那么再提交时会报错了 java.util.concurrent.RejectedExecutionException
        // executorService.execute(new ShutDownTask());
        //isTerminated()(是否完全结束,比如还有线程处于关闭过程中也算未完全终止)
        log.info("是否终止线程:" + executorService.isTerminated());
        //awaitTermination(3L, TimeUnit.SECONDS)一定时间累监测一下,也就是shutdown()处于关闭完了没有,只是监测,判断
        log.info("监测线程是否终止1: " + executorService.awaitTermination(3L, TimeUnit.SECONDS));
        log.info("监测线程是否终止2: " + executorService.awaitTermination(3L, TimeUnit.SECONDS));
        //设置时间保证上面的shutdown()已经关闭完成了,不存在关闭中的线程,再看
        Thread.sleep(10000);
        log.info("是否终止线程:" + executorService.isTerminated());


    }


}

